package com.vecspace.framework.sysdata.dao;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import com.vecspace.database.dao.AbstractDao;

@Repository("sys_data_table_dao")
public class SysDataTableDao extends AbstractDao{
	
	/**获取表的id
	 * 
	 * @param tableName
	 * @param schema
	 * @param autoInsert 如果没有注册此表，是否进行注册
	 * @return
	 * @throws Exception
	 */
	public Long getTableId(String tableName, String schema, boolean autoInsert) throws Exception {
		tableName = tableName.trim().toUpperCase();
		Long tableId;
		if(StringUtils.isBlank(schema)) {
			String sql = "select id from tm_sys_table_info where table_name=? and (db_schema is null or db_schema='')";
			tableId = dao.queryLong(sql, new Object[] {tableName});
		}else {
			String sql = "select id from tm_sys_table_info where table_name=? and db_schema=?";
			tableId = dao.queryLong(sql, new Object[] {tableName, schema});
		}
		if(tableId == null || tableId == 0) {
			if(autoInsert) {
				String sql = "insert into tm_sys_table_info(table_name, db_schema) values(?, ?)";
				dao.insertDataRowBySql(sql, new Object[] {tableName, schema});
				tableId = getTableId(tableName, schema, false);
			}
		}
		return tableId;
	}
	
	/**获取字段的id
	 * 
	 * @param tableId
	 * @param columnName
	 * @param autoInsert 如果没有注册此字段，是否进行注册
	 * @return
	 * @throws Exception
	 */
	public Long getColumnId(Long tableId, String columnName, boolean autoInsert) throws Exception {
		columnName = columnName.toUpperCase();
		String sql = "select id from TM_SYS_TABLE_COLUMN where TABLE_ID=? and COLUMN_NAME=?";
		Long columnId = dao.queryLong(sql, new Object[] {tableId, columnName});
		if(columnId == null || columnId == 0) {
			if(autoInsert) {
				sql = "insert into TM_SYS_TABLE_COLUMN(TABLE_ID, COLUMN_NAME) values(?,?)";
				dao.insertDataRowBySql(sql, new Object[] {tableId, columnName});
				columnId = this.getColumnId(tableId, columnName, false);
			}
		}
		return columnId;
	}
}
